#!/bin/bash

# Flush any current firewall settings
iptables -F

# Allow all established connections 
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# state is deprecated in favor of conntrack but on most systems, both work. 
# On some systems like the Wheezy image for ODROID-U2/U3 devices, state is
# not available and result in "iptables: No chain/target/match by that name."
if [ $? -ne 0 ]; then
   # Allow all established connections with conntrack if state is missing
   iptables -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
fi
      
# Allow all loopback traffic.
iptables -I INPUT 1 -i lo -j ACCEPT

# Allow all SSH traffic.
iptables -A INPUT -p tcp --dport ssh -j ACCEPT

# Allow for all traffic from anywhere for the following services.
iptables -A INPUT -p tcp --dport 80 -j ACCEPT          # nginx
iptables -A INPUT -p tcp --dport 443 -j ACCEPT         # nginx (SSL)
iptables -A INPUT -p tcp --dport 5222 -j ACCEPT        # ejabberd
iptables -A INPUT -p tcp --dport 8080:8099 -j ACCEPT   # nginx -> Google App Engine
iptables -A INPUT -p tcp --dport 4380:4400 -j ACCEPT   # nginx -> Google App Engine (SSL)
iptables -A INPUT -p tcp --dport 17443 -j ACCEPT       # AppController
iptables -A INPUT -p tcp --dport 17441 -j ACCEPT       # AdminServer

# The following line enables debugging tools, viewers for queues and
# datastore.
#iptables -A INPUT -p tcp --dport 5555 -j ACCEPT       # Celery Flower
#iptables -A INPUT -p tcp --dport 8100:8119 -j ACCEPT  # datastore viewer

# Uncomment the following line to enable TaskQueue REST API access.
#iptables -A INPUT -p tcp --dport 8199 -j ACCEPT        # TaskQueue REST API Endpoint

# Dashboard
# Note: If you are using Shibboleth for authentication, uncomment and edit the
# following two lines to restrict access to the dashboard.

# APPSCALE_DNS=dns-for-your-appscale-instance.com
# SHIBBOLETH_CONNECTOR=your-shibboleth-connector.com

if [ -n "$APPSCALE_DNS" ] && [ -n "$SHIBBOLETH_CONNECTOR" ]; then
  DASHBOARD_SOURCE="-s ${APPSCALE_DNS},${SHIBBOLETH_CONNECTOR}"
fi
iptables -A INPUT ${DASHBOARD_SOURCE} -p tcp --dport 1080 -j ACCEPT
iptables -A INPUT ${DASHBOARD_SOURCE} -p tcp --dport 1443 -j ACCEPT

ALL_IPS_FILE=/etc/appscale/all_ips

# Allow any connections between AppScale nodes
cat $ALL_IPS_FILE 2> /dev/null | sort -u | while read line; do
  test -n "$line" && iptables -A INPUT -s ${line} -j ACCEPT
done

# Drop all other connections
iptables -A INPUT -j DROP
